"ui";
engines.all().map((ScriptEngine) => {
  if (engines.myEngine().toString() !== ScriptEngine.toString()) {
    ScriptEngine.forceStop();
  }
});
importClass(Packages.androidx.recyclerview.widget.RecyclerView);
importClass(Packages.androidx.recyclerview.widget.LinearLayoutManager);
importClass(android.graphics.Color);
importClass(Packages.androidx.swiperefreshlayout.widget.SwipeRefreshLayout);
importClass(android.view.View);
require("./component/button-layout");
require("./component/data-show");
require("./component/test-button");
require("./component/scale-viewpager");
let yashuUtil = require("./yashuUtil");
let config = require("./config");
let service = require("./service");

let themeColor = config.themeColor;
let status_bar_height = yashuUtil.status_bar_height;
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
let userInfo = config.storage.get("userInfo");
let avatar_url = userInfo.avatar_url;

ui.layout(
  <vertical bg="{{themeColor}}" paddingTop="{{status_bar_height}}px">
    <scale-viewpager id="viewpager">
      {/**drawer侧边栏 */}
      <relative w="*" clickable="true">
        <relative id="drawerToolbar" marginTop="10">
          <img id="icon" w="40" h="40" margin="20 0" scaleType="fitXY" circle="true" src="{{avatar_url}}" />

          <text
            id="title"
            layout_toRightOf="icon"
            layout_alignParentTop="true"
            w="auto"
            h="auto"
            text="{{userInfo.name}}"
            textSize="16sp"
            textStyle="bold"
            textColor="#ffffff"
            typeface="monospace"
          />

          <text
            id="subtitle"
            layout_toRightOf="icon"
            layout_below="title"
            w="auto"
            h="auto"
            text="{{userInfo.remark}}"
            textSize="12sp"
            textStyle="bold"
            textColor="#7fffffff"
            typeface="monospace"
          />
        </relative>

        <frame id="drawerFrame" layout_below="drawerToolbar" layout_above="drawerHorizontal" h="*">
          <list id="drawerList" w="auto" h="auto" padding="0 20" layout_gravity="center_vertical">
            <button-layout w="*" text="{{this.text}}" leftDrawable="{{this.drawable}}" />
          </list>
        </frame>

        <horizontal id="drawerHorizontal" layout_alignParentBottom="true">
          <button-layout id="settings" text="设置" leftDrawable="ic_settings_black_48dp" />
          <View bg="#ffffff" w="2px" h="16" layout_gravity="center_vertical" />
          <button-layout id="signOut" text="退出" leftDrawable="ic_exit_to_app_black_48dp" />
        </horizontal>
      </relative>
      {/** 动态界面 */}
      <data-show id="eventsData"></data-show>
      <data-show id="repoData"></data-show>
    </scale-viewpager>
  </vertical>
);

/* -------------------------------------------------------------------------- */
let viewpager = ui.viewpager;
var len = viewpager.childCount;
for (var i = 0; i < len; i++) {
  let page = viewpager.getChildAt(i);
  page.setTag(i);
}
viewpager.overScrollMode = View.OVER_SCROLL_NEVER; //删除滑动到底的阴影
// viewpager序号从0开始
viewpager.currentItem = 1; //跳转到1号子页面
let first = true;
ui.viewpager.setPageTransformer(true, new MyPageTransform(ui.viewpager)); //设置viewpager切换动画
var items = [
  {
    text: "动态",
    drawable: "ic_list_black_48dp",
  },
  {
    text: "仓库",
    drawable: "ic_view_module_black_48dp",
  },
  {
    text: "fork",
    drawable: "ic_library_add_black_48dp",
  },
  {
    text: "Q群",
    drawable: "ic_group_black_48dp",
  },
];
ui.drawerList.setDataSource(items);
ui.drawerList.overScrollMode = View.OVER_SCROLL_NEVER;
//列表控件点击事件
ui.drawerList.on("item_click", (item) => {
  if (item.text === "仓库") {
    ui.viewpager.currentItem = 2;
    ui.repoData.widget.init(ui.repoData);
  } else if (item.text === "fork") {
    engines.execScriptFile("./page/fork.js");
  } else if (item.text === "Q群") {
    app.startActivity({
      action: "android.intent.action.VIEW",
      data: "mqqapi://card/show_pslcard?src_type=internal&version=1&uin=582976637&card_type=group&source=code",
    });
  } else if (item.text === "动态") {
    ui.viewpager.currentItem = 1;
    ui.eventsData.widget.init(ui.eventsData);
  }
});
/* -------------------------------------------------------------------------- */
ui.settings.on("click", () => {
  toastLog("settings 待添加");
});

ui.signOut.on("click", () => {
  toastLog("退出");
  config.storage.clear();
  engines.execScriptFile("./page/login.js");
});
/* -------------------------------------------------------------------------- */

yashuUtil.setStatusBarFullTransparent();
/* ---------------------设置动态页面数据----------------------------------------------------- */
ui.eventsData.widget.setTitle("动态");
ui.eventsData.widget.setMoreMenuAction(function () {
  ui.viewpager.currentItem = 0; //跳转到1号子页面
});
ui.eventsData.widget.setRequestData(service.getUserEvents);
ui.eventsData.widget.setBindViewHolder(function (items) {
  return function (holder, position) {
    // 数据绑定
    let item = items[position];
    let view = holder.itemView;
    if (!item.payload) {
      view.content.setText("未知操作");
      view.side.setBackgroundColor(item.color);
      return;
    }
    if (item.type === "ForkEvent") {
      let humanType = config.actionType[item.type];
      view.content.setText(humanType + "仓库" + item.repo.human_name);
      view.side.setBackgroundColor(item.color);

      let repoUrl = item.actor.html_url + "/" + item.repo.full_name.split("/").pop();
      item.repoUrl = repoUrl;
      return;
    }
    let humanType = config.actionType[item.type];
    let ref_type = item.payload.ref_type;
    let humanRefType = config.refType[ref_type];
    let human_name = item.repo.human_name;
    if (humanType && humanRefType) {
      if (ref_type === "repository") {
        let content = humanType + " " + humanRefType + " " + human_name;
        view.content.setText("" + content);
        view.side.setBackgroundColor(item.color);
      } else {
        let content = humanType + " " + humanRefType + " " + item.payload.ref + " 到 " + human_name;
        view.content.setText("" + content);
        view.side.setBackgroundColor(item.color);
      }
    } else {
      let payloadRef = item.payload.ref;
      // payloadRef以refs开头
      if (payloadRef.indexOf("refs") === 0) {
        let arr = payloadRef.split("/");
        let branchName = arr[arr.length - 1];
        let content = humanType + " " + human_name + " 的 " + branchName + " 分支";
        view.content.setText("" + content);
        view.side.setBackgroundColor(item.color);
      } else {
        view.content.setText("" + JSON.stringify(item));
        view.side.setBackgroundColor(item.color);
      }
    }
    let repoUrl = item.actor.html_url + "/" + item.repo.full_name.split("/").pop();
    item.repoUrl = repoUrl;
  };
});
/* ---------------------设置仓库列表页面数据----------------------------------------------------- */
ui.repoData.widget.setTitle("仓库");
ui.repoData.widget.setMoreMenuAction(function () {
  ui.viewpager.currentItem = 0; //跳转到1号子页面
});
ui.repoData.widget.setRequestData(service.getRepos);
ui.repoData.widget.setBindViewHolder(function (items) {
  return function (holder, position) {
    // 数据绑定
    let item = items[position];
    let view = holder.itemView;
    view.content.setText("" + item.name);
    view.side.setBackgroundColor(item.color);

    let repoUrl = item.namespace.html_url + "/" + item.name;
    item.repoUrl = repoUrl;
  };
});
/* ------------------自定义函数-------------------------------------------------------- */

/**
 * 自定义viewpager动画
 */
function MyPageTransform(viewpager) {
  var pageWidth;
  this.transformPage = function (view, position) {
    pageWidth = view.getWidth();
    // 如果是第二页, 并且是从左往右滑动, 才执行缩放
    if (viewpager.widget.scrollPosition === 0 && !viewpager.widget.isMoveFromLeftToRight() && view.getTag() === 1) {
      if (position < 1 && position > 0) {
        view.setTranslationX(pageWidth * 0.5 * -position);
        // 缩放view的宽高
        view.setScaleX(1 - 0.3 * position);
        view.setScaleY(1 - 0.3 * position);
      }
    }
  };
}
